<template>
  <div class="file">
    <!-- <input type="file" multiple>
    <el-button>开始上传</el-button>-->
    <el-card class="upload">
      <!-- <input type="file" class="file-demo">
      <button @click="submit">上传</button>-->
      <el-upload
        class="upload-demo"
        ref="upload"
        action
        drag
        :accept="fileTypes"
        :auto-upload="false"
        :on-change="handleImport"
        :http-request="uploadFile"
        :on-progress="process"
        name="file"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__text">可上传.jpg,.png,.pdf,.xls,.xlsx,.doc,.docx,.pptx,.PDF文件</div>
      </el-upload>
      <div class="subject">
        <el-form label-width="100px">
          <el-form-item label="科目">
            <el-select v-model="subject" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.subject"
                :label="item.label"
                :value="item.subject"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资源名">
            <el-input v-model="resname" placeholder="请输入资源名" class="resname"></el-input>
          </el-form-item>
          <el-form-item label="最少观看时间" prop="spendtime">
            <el-input-number
              v-model="spendtime"
              controls-position="right"
              @change="handleChange"
              :min="0"
              :max="180"
            ></el-input-number>分钟
          </el-form-item>
          <el-form-item label="是否可下载">
            <el-switch v-model="isdownload" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-form-item>
          <el-form-item label="是否必学">
            <el-switch v-model="isuse" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn">
        <el-button size="small" type="primary" style="margin-right:10px;" @click="submitUpload">确定</el-button>
        <el-button size="small" @click="handleCancel">取消</el-button>
      </div>
    </el-card>
    <!-- <el-card class="list">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="文件名" width="180"></el-table-column>
        <el-table-column label="上传进度" width="180">
          <el-progress :percentage="progressPercent"></el-progress>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="180"></el-table-column>
        <el-table-column label="上传状态" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 1">准备上传</span>
            <span v-if="scope.row.status === 4" style="color: brown">上传失败</span>
            <span v-if="scope.row.status === 5" style="color: chartreuse">已上传</span>
            <el-progress v-if="scope.row.status === 2" :text-inside="true" :stroke-width="20" :percentage="scope.row.percent"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-card> -->
  </div>
</template>

<script>
import axios from "axios";
import Message from "@/plugins/message";
export default {
  data() {
    return {
      options: [],
      subject: "",
      fileTypes: ".jpg,.png,.pdf,.xls,.xlsx,.doc,.docx,.pptx,.PDF",
      tableData: [
        {
          name: "MHK",
          process: "已完成",
          size: "1.2M",
          state: "已完成"
        }
      ],
      spendtime: 60,
      resname: "",
      isuse: true,
      isdownload: true,
      fileData: "",
      fileList: [],
      // progressPercent: 0
    };
  },
  created() {
    var that = this;
    axios.get("/subSelectAll").then(res => {
      // let { code, message, data } = res.data;
      console.log(res);
      // let len = data.length;
      // for (let i = 0; i < len; i++) {
      //   let sub = { subject: data[i].subname, label: data[i].subname };
      //   that.options.push(sub);
      // }
      // // console.log(that.options[0].subject);
      // that.subject= that.options.length!=0 ? that.options[0].subject:"";
    // console.log(that.subject)
    });
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    process(e,file,fileList){
      console.log(file,fileList);
    },
    change(limit) {
      var size = "";
      if (limit < 0.1 * 1024) {
        //小于0.1KB，则转化成B
        size = limit.toFixed(2) + "B";
      } else if (limit < 0.1 * 1024 * 1024) {
        //小于0.1MB，则转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        //小于0.1GB，则转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }

      var sizeStr = size + ""; //转成字符串
      var index = sizeStr.indexOf("."); //获取小数点处的索引
      var dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
      if (dou == "00") {
        //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
      }
      return size;
    },
    // submit(){
    //   let file = document.getElementsByClassName("file-demo")[0].files[0];
    //   this.fileData = new FormData();
    //   this.fileData.append("file",file);
    //   this.fileData.append("resname",this.resname);
    //   this.fileData.append("subject",this.subject);
    //   this.fileData.append("spendtime",this.spendtime);
    //   this.fileData.append("isuse",this.isuse);
    //   this.fileData.append("isdownload",this.isdownload);
    //   var that = this;
    //   axios({
    //     method: "post",
    //     url: "/upload/",
    //     data: that.fileData,
    //     headers:{
    //           'Content-Type':'multipart/form-data'
    //         }
    //   }).then(res => {
    //     console.log(res);
    //   });
    //   console.log(file);
    // },
    handleImport(file, fileList) {
      // console.log(file);
      if(this.fileList.length == 0){
        this.fileList.push(file);
      }else{
        this.fileList.pop();
        this.fileList.push(file);
      }
      // console.log(file);
      // console.log(fileList);
    },
    uploadFile(file) {
      // console.log(file.file);
      let obj = {
        name: file.file.name,
        size: this.change(file.file.size),
        progressPercent: this.progressPercent,
        status: 1
      };
      this.tableData.push(obj);
      this.fileData = new FormData();
      let type = file.file.name.split(".")[1];
      this.fileData.append("file", file.file);
      this.fileData.append("resname", this.resname);
      this.fileData.append("subject", this.subject);
      this.fileData.append("spendtime", this.spendtime);
      this.fileData.append("isuse", this.isuse);
      this.fileData.append("isdownload", this.isdownload);
      this.fileData.append("type",type);
      var that = this;
      // const config = {
      //   headers: {
      //     "Content-Type": "multipart/form-data"
      //   },
      //   }
      //   // file.onProgress({ percent: percentCompleted })
      // };
      
        axios({
          method:"post",
          url:"/upload/",
          data:that.fileData,
          headers: {
          "Content-Type": "multipart/form-data"
        },
        })
        .then(res => {
          let {code,message,data} = res.data;
          file.onSuccess();
          if(code == 200){
            Message.success(message);
            this.$router.push("/docmangement/mangement");
          }else{
            file.onError();
            Message.error("上传失败");
          }
        });
    },
    submitUpload() {
      if (this.fileList.length == 0) {
        this.$message.error("请选择文件");
        return;
      }
      let len = this.fileList.length;
      // this.fileData = new FormData();
      // console.log(this.fileList[0]);

      // console.log(this.fileData);
      // :data="{resname,subject,isuse,isdownload}"
      // console.log(this.fileData)
      // console.log(this.fileData);
      this.$refs.upload.submit();

      // var that = this;
    },
    handleCancel() {}
    // handleUpload(file) {
    //   console.log(file);
    // },
    // handleProgress(event, file, fileList) {
    //   console.log(file, fileList);
    // },
    // handleChange(file, fileList) {
    //   this.fileList = fileList.slice(-3);
    // },
    // handleRemove(file, fileList) {
    //   console.log(file, fileList);
    // },
    // handleSuccess(file, fileList) {
    //   console.log(file, fileList);
    // },
    // handlePreview(file) {
    //   console.log(file);
    // },
    // handleExceed(files, fileList) {
    //   this.$message.warning(
    //     `当前限制选择 3 个文件，本次选择了 ${
    //       files.length
    //     } 个文件，共选择了 ${files.length + fileList.length} 个文件`
    //   );
    // },
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${file.name}？`);
    // },
    // handlePost(file) {
    //   // action="/docmanager/external/upload"
    //   var data = document.getElementById("load");
    //   const fd = new window.FormData(data);
    //   fd.append("categoryId", 1);
    //   fd.append("tag", 2);
    //   fd.append("description", 3);
    //   fd.append("prefix", 4);
    //   fd.append("file", file);
    //   // console.log(fd);

    //   // // 配置post请求的参数。参数名file,后面跟要传的文件，参数名fileType，值为category（看后端的具体要求）
    //   // // fd.append('file', file)
    //   // postUpload(fd).then(response => {
    //   //   console.log(1);
    //   //   console.log(response);
    //   //   console.log(file);
    //   //   console.log(2);
    //   // })
    // }
  }
};
</script>
<style scoped>
.file {
  display: flex;
  justify-content: center;
  align-content: center;
}
.upload {
  width: 400px;
  /* border: 1px solid black; */
}
.upload el-uploader {
  width: 100px;
  border: 1px solid black;
  border-radius: 10%;
}
.subject {
  margin-top: 20px;
}
.resname,
.spendtime {
  width: 218px;
}
.list {
  margin-left: 40px;
}
.btn {
  display: flex;
  /* justify-content: center; */
  /* border: 1px solid black; */
  padding-left: 100px;
  /* margin:0 auto; */
}
</style>
